package cn.tedu.article.service.impl;

import cn.tedu.article.dao.repository.ArticleRepository;
import cn.tedu.article.pojo.param.*;
import cn.tedu.article.pojo.vo.ArticleVO;
import cn.tedu.article.pojo.vo.CategoryVO;
import cn.tedu.article.pojo.vo.TagVO;
import cn.tedu.article.service.ArticleService;
import cn.tedu.article.util.XingHuoHttpClientUtil;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleRepository articleRepository;

    @Override
    public ArticleVO saveArticle(ArticleSaveParam articleSaveParam) {
        log.debug("调用保存文章服务, 参数:{}",articleSaveParam);
        ArticleVO articleVO = articleRepository.saveArticle(articleSaveParam);
        log.debug("调用保存文章服务成功, 参数:{}",articleSaveParam);
        return articleVO;
    }

    @Override
    public void deleteArticle(Long articleId) {
        log.debug("调用删除文章服务, 参数:{}",articleId);
        articleRepository.deleteArticle(articleId);
        log.debug("调用删除文章服务成功, 参数:{}",articleId);
    }

    @Override
    public ArticleVO selectArticleById(Long articleId,Long userId) {
        log.debug("调用通过id查文章服务, 参数:{}",articleId);
        ArticleVO articleVO = articleRepository.selectArticleById(articleId,userId);
        log.debug("调用通过id查文章服务成功, 参数:{}",articleId);
        return articleVO;
    }

    @Override
    public List<ArticleVO> selectArticleByUserId(Long userId) {
        log.debug("调用通过用户id查文章服务, 参数:{}",userId);
        List<ArticleVO> articleVOList = articleRepository.selectArticleByUserId(userId);
        log.debug("调用通过用户id查文章服务成功, 参数:{}",userId);
        return articleVOList;
    }

    @Override
    public List<ArticleVO> selectArticleByArticleQueryParam(ArticleQueryParam articleQueryParam) {
        log.debug("通过文章查询对象查询文章服务, 参数:{}",articleQueryParam);
        List<ArticleVO> articleVOList = articleRepository.selectArticleByArticleQueryParam(articleQueryParam);
        log.debug("通过文章查询对象查询文章服务成功, 参数:{}",articleQueryParam);
        return articleVOList;
    }

    @Override
    public List<TagVO> selectArticleTags(ArticleTagQueryParam articleTagQueryParam) {
        log.debug("查询文章标签服务:{}",articleTagQueryParam);
        List<TagVO> tagVOList = articleRepository.selectArticleTags(articleTagQueryParam);
        log.debug("查询文章标签服务成功:{}",articleTagQueryParam);
        return tagVOList;
    }

    @Override
    public List<CategoryVO> selectArticleCategory(ArticleCategoryQueryParam articleCategoryQueryParam) {
        log.debug("查询分类服务:{}",articleCategoryQueryParam);
        List<CategoryVO> categoryVOList = articleRepository.selectArticleCategory(articleCategoryQueryParam);
        log.debug("查询分类服务成功:{}",articleCategoryQueryParam);
        return categoryVOList;
    }

    @Override
    public void articleOnLike(Integer articleId, Integer userId) {
        log.debug("文章点赞:{}",articleId);
        articleRepository.articleOnLike(articleId,userId);
        log.debug("文章点赞,成功:{}",articleId);
    }

    @Override
    public void articleOnFavorite(Integer articleId, Integer userId) {
        log.debug("文章收藏:{}",articleId);
        articleRepository.articleOnFavorite(articleId,userId);
        log.debug("文章收藏,成功:{}",articleId);
    }

    @Override
    public void articleCancelLike(Integer articleId, Integer userId) {
        log.debug("取消文章点赞:{}",articleId);
        articleRepository.articleCancelLike(articleId,userId);
        log.debug("取消文章点赞,成功:{}",articleId);
    }

    @Override
    public void articleCancelFavorite(Integer articleId, Integer userId) {
        log.debug("取消文章收藏:{}",articleId);
        articleRepository.articleCancelFavorite(articleId,userId);
        log.debug("取消文章收藏,成功:{}",articleId);
    }

    @Override
    public void articleVisit(Integer articleId) {
        log.debug("文章浏览记录服务:{}",articleId);
        articleRepository.articleVisit(articleId);
        log.debug("文章浏览记录服务,成功:{}",articleId);
    }

    @Override
    public void visitAI(ResponseBodyEmitter emitter, AiRecordSaveParam aiRecordSaveParam) {
        Long userId = aiRecordSaveParam.getUserId();
        String userInput = aiRecordSaveParam.getUserInput();
        String url = "https://spark-api-open.xf-yun.com/v1/chat/completions";

        Map<String,Object> map = new ConcurrentHashMap<>();
        map.put("model","generalv3");
        map.put("stream",true);
        map.put("max_tokens",500);

        Map<String,String> system = new ConcurrentHashMap <>();
        system.put("role","system");
        system.put("content","你是一名程序员,根据提供的文档末尾，续写内容，要求内容详细、步骤清晰，语言通俗易懂，请提供必要的代码示例和解释，确保回复内容的实用性和可读性。");
        Map<String,String> user = new ConcurrentHashMap <>();
        user.put("role","user");
        user.put("content",userInput.trim());

        ArrayList<Map<String,String>> messages = new ArrayList<>();
        messages.add(system);
        messages.add(user);
        map.put("messages",messages);

        Gson gson = new Gson();

        String body = gson.toJson(map);
        log.debug(body);



     /*   JSONObject json = new JSONObject();
        json.put("model","generalv3");
        json.put("max_tokens",500);
        json.put("stream","false");

        String messagesJson = "[{" +
                "\"role\": \"system\"," +
                "\"content\": \"你是一名资深程序员请根据提供内容，续写一篇编程博客的内容，要求内容详细、步骤清晰，语言通俗易懂，适合不同水平的读者，请提供必要的代码示例和解释，确保文章的实用性和可读性。\"\n" +
                "},{" +
                "\"role\": \"user\"," +
                "\"content\": \""+ userInput +
                "}]";
        json.put("messages",messagesJson);
        log.debug(json.toString());*/
//
//        String body=
//                "{\n" +
//                "    \"model\":\"generalv3\",\n" +
//                "    \"max_tokens\": 500 ,\n" +
//                "    \"messages\": [\n" +
//                "        {\n" +
//                "            \"role\": \"system\",\n" +
//                "            \"content\": \"你是一名资深程序员请根据提供内容，续写一篇编程博客的内容，要求内容详细、步骤清晰，语言通俗易懂，适合不同水平的读者，请提供必要的代码示例和解释，确保文章的实用性和可读性。\"\n" +
//                "        },\n" +
//                "        {\n" +
//                "            \"role\": \"user\",\n" +
//                "            \"content\": \""+ userInput.trim().replace("\"","\\\"") +"\"\n" +
//                "        }\n" +
//                "    ],\n" +
//                "    \"stream\": true\n" +
//                "}";
//        log.debug(body);



        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer iZbaDUrFvjALzAbFbY:EOIrvAoDrrluNDRIPOE");

//        HttpEntity<String> stringHttpEntity = new HttpEntity<>(body, headers);
//        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url, stringHttpEntity, String.class);
////        String AIReply = XingHuoHttpClientUtil.doPostJson(url, json);
//        log.debug(stringResponseEntity.toString());

        String aiContent = XingHuoHttpClientUtil.doPostJson(emitter,url, body);
        log.debug("ai回复完整内容"+aiContent);
        AiRecordSaveParam param = new AiRecordSaveParam();
        param.setUserId(userId);
        param.setUserInput(userInput);
        param.setAiContent(aiContent);
        param.setStatus((byte) 0);
        param.setReplyTime(new Date());
        articleRepository.saveAiRecord(param);

        /*try{
        System.out.println(userInput);
        String[] message =[{},{}]
        String url = "https://spark-api-open.xf-yun.com/v1/chat/completions";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "Bearer iZbaDUrFvjAvLLzAbFbY:EbOIrvAoDrrluNDRIPOE");

        con.setDoOutput(true);

        // 发送POST请求参数
        String jsonInputString = "{\"model\": \"generalv3\"," +"\"max_tokens\": 500," + "\"messages\": [" + "{\"role\": \"system\"," + "\"content\": \"你是一名资深程序员请根据提供内容，续写一篇编程博客的内容，要求内容详细、步骤清晰，语言通俗易懂，适合不同水平的读者，请提供必要的代码示例和解释，确保文章的实用性和可读性。\"" + "},{" + "\"role\": \"user\"," + "\"content\": \"" + userInput.replace("\"", "\\\"") + "\"" + "}],\"stream\": true}";
        log.debug(jsonInputString);
        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.writeBytes(jsonInputString);
            wr.flush();
        }

        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
                try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        // 处理流式响应，逐步发送给客户端
                        emitter.send(inputLine);
                    }
                }
            } else {
                // 错误处理
                emitter.completeWithError(new RuntimeException("Server returned HTTP error code: " + responseCode));
            }
            con.disconnect();
        } catch (Exception e) {
            emitter.completeWithError(e);
        } finally {
            // 确保在所有情况下都完成emitter
            emitter.complete();
        }*/

    }
}
